package org.dromara.wmscloud.service.impl;

import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.wmscloud.domain.vo.BaseWarehouseVo;
import org.dromara.wmscloud.mapper.BaseWarehouseMapper;
import org.springframework.stereotype.Service;
import org.dromara.wmscloud.domain.bo.BaseLocationBo;
import org.dromara.wmscloud.domain.vo.BaseLocationVo;
import org.dromara.wmscloud.domain.BaseLocation;
import org.dromara.wmscloud.mapper.BaseLocationMapper;
import org.dromara.wmscloud.service.IBaseLocationService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 货位Service业务层处理
 *
 * @author hou
 * @date 2025-04-03
 */
@RequiredArgsConstructor
@Service
public class BaseLocationServiceImpl implements IBaseLocationService {

    private final BaseLocationMapper baseLocationMapper;
    private final BaseWarehouseMapper warehouseMapper;

    /**
     * 查询货位
     *
     * @param locationId 主键
     * @return 货位
     */
    @Override
    public BaseLocationVo queryById(Long locationId) {
        return baseLocationMapper.selectVoById(locationId);
    }

    /**
     * 分页查询货位列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 货位分页列表
     */
    @Override
    public TableDataInfo<BaseLocationVo> queryPageList(BaseLocationBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<BaseLocation> lqw = buildQueryWrapper(bo);
        Page<BaseLocationVo> result = baseLocationMapper.selectVoPage(pageQuery.build(), lqw);
        List<BaseLocationVo> records = result.getRecords();
        if (!records.isEmpty()) {
            fillWarehouseName(records);
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的货位列表
     *
     * @param bo 查询条件
     * @return 货位列表
     */
    @Override
    public List<BaseLocationVo> queryList(BaseLocationBo bo) {
        LambdaQueryWrapper<BaseLocation> lqw = buildQueryWrapper(bo);
        List<BaseLocationVo> list = baseLocationMapper.selectVoList(lqw);
        if (!list.isEmpty()) {
            fillWarehouseName(list);
        }
        return list;
    }

    private LambdaQueryWrapper<BaseLocation> buildQueryWrapper(BaseLocationBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BaseLocation> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(BaseLocation::getLocationId);
        lqw.eq(StringUtils.isNotBlank(bo.getWarehouseCode()), BaseLocation::getWarehouseCode, bo.getWarehouseCode());
        lqw.eq(StringUtils.isNotBlank(bo.getLocationCode()), BaseLocation::getLocationCode, bo.getLocationCode());
        lqw.like(StringUtils.isNotBlank(bo.getLocationName()), BaseLocation::getLocationName, bo.getLocationName());
        lqw.like(StringUtils.isNotBlank(bo.getLocationType()), BaseLocation::getLocationType, bo.getLocationType());
        return lqw;
    }

    /**
     * 新增货位
     *
     * @param bo 货位
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(BaseLocationBo bo) {
        BaseLocation add = MapstructUtils.convert(bo, BaseLocation.class);
        validEntityBeforeSave(add);
        boolean flag = baseLocationMapper.insert(add) > 0;
        if (flag) {
            bo.setLocationId(add.getLocationId());
        }
        return flag;
    }

    /**
     * 修改货位
     *
     * @param bo 货位
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(BaseLocationBo bo) {
        BaseLocation update = MapstructUtils.convert(bo, BaseLocation.class);
        validEntityBeforeSave(update);
        return baseLocationMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BaseLocation entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除货位信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseLocationMapper.deleteByIds(ids) > 0;
    }

    /**
     * 批量填充仓库名称字段
     */
    private void fillWarehouseName(List<BaseLocationVo> list) {
        Set<String> warehouseCodes = list.stream()
            .map(BaseLocationVo::getWarehouseCode)
            .filter(Objects::nonNull)
            .collect(Collectors.toSet());

        if (warehouseCodes.isEmpty()) {
            return;
        }

        Map<String, String> warehouseNameMap = Optional.ofNullable(warehouseMapper.selectNamesByCodes(warehouseCodes))
            .orElse(Collections.emptyList())
            .stream()
            .collect(Collectors.toMap(BaseWarehouseVo::getWarehouseCode, BaseWarehouseVo::getWarehouseName, (a, b) -> a));

        list.forEach(vo -> vo.setWarehouseName(warehouseNameMap.get(vo.getWarehouseCode())));
    }
}
